package com.coolbi.common.util;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

public class JsonSfUtil {

	/**
	 * 将字符串转为对象
	 * 
	 * @param jsonString
	 * @return
	 */
	public static Object toObject(String jsonString) {

		return JSONObject.fromObject(jsonString);

	}

	/**
	 * 将字符串转为数组
	 * 
	 * @param jsonArrayString
	 * @return
	 */
	public static Object[] toArray(String jsonArrayString) {
		try {
			if (jsonArrayString==null||"".equals(jsonArrayString.trim())) {
				return null;
			}
			return JSONArray.fromObject(jsonArrayString).toArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	/**
	 * 将对象转换为JSON字符串
	 * 
	 * @param object
	 * @return
	 */
	public static String toJsonByJsonLib(Object object) {
		JsonConfig jsonConfig = new JsonConfig();
		
		//jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss SSS"));  
		
		/*
		jsonConfig.registerDefaultValueProcessor(Integer.class,
				new DefaultValueProcessor() {
					@Override
					public Object getDefaultValue(Class arg0) {
						return 0;
					}
				});
		jsonConfig.registerDefaultValueProcessor(Long.class,
				new DefaultValueProcessor() {
					@Override
					public Object getDefaultValue(Class arg0) {
						return 0;
					}
				});
				*/
		JSONObject jsonArray = JSONObject.fromObject(object, jsonConfig);

		return jsonArray.toString();
	}
	
	/**
	 * 将对象转换为JSON字符串
	 * 
	 * @param object
	 * @return
	 */
	public static String toJsonByJsonLib(Object object,final String...fields) {
		JsonConfig jsonConfig = new JsonConfig();
		
		//jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss SSS"));  
		
		jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				for (String propName : fields) {
					if (name.equals(propName)) {
						return false;
					}
				}
				return true;
			}
		});

		JSONObject jsonArray = JSONObject.fromObject(object, jsonConfig);

		return jsonArray.toString();
	}
	
	/**
	 * 将对象转换为JSON字符串
	 * 
	 * @param object
	 * @return
	 */
	public static String toJsonByReject(Object object,final String...rejects) {
		JsonConfig jsonConfig = new JsonConfig();
		
		//jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss SSS"));  
		
		jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				for (String propName : rejects) {
					if (name.equals(propName)) {
						return true;
					}
				}
				return false;
			}
		});

		JSONObject jsonArray = JSONObject.fromObject(object, jsonConfig);

		return jsonArray.toString();
	}
}